<%@ page contentType="application/json;charset=UTF-8" language="java" %><%--
--%><%@ page import="java.util.Collection" %><%--
--%><%@ page import="o.json.JSONFactory" %><%--
--%><%@ page import="o.json.JSONValue" %><%--
--%><%@ page import="o.json.JSONWriter" %><%--
--%><%@ page import="o.json.JSONWriter2" %><%--
--%><%@ page import="com.google.appengine.api.users.User" %><%--
--%><%@ page import="com.google.appengine.api.users.UserService" %><%--
--%><%@ page import="com.google.appengine.api.users.UserServiceFactory" %><%--
--%><%@ page import="wwiii.Area" %><%--
--%><%@ page import="wwiii.AreaMap" %><%--
--%><%@ page import="wwiii.Game" %><%--
--%><%@ page import="wwiii.GameManager" %><%--
--%><%

	final UserService us = UserServiceFactory.getUserService();
	if (!us.isUserLoggedIn()) {
		response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
		return;
	}
	final User user = us.getCurrentUser();

	String id = request.getParameter("id");
	if (id == null || id.isEmpty()) {
		response.sendError(HttpServletResponse.SC_BAD_REQUEST, "id is not valid '"+ id +"'");
		return;
	}
	String fromId = request.getParameter("from");
	if (fromId == null || fromId.isEmpty()) {
		response.sendError(HttpServletResponse.SC_BAD_REQUEST, "from is not valid '"+ fromId +"'");
		return;
	}
	String toId = request.getParameter("to");
	if (toId == null || toId.isEmpty()) {
		response.sendError(HttpServletResponse.SC_BAD_REQUEST, "to is not valid '"+ toId +"'");
		return;
	}
	String sforce = request.getParameter("force");
	if (sforce == null || sforce == "") {
		response.sendError(HttpServletResponse.SC_BAD_REQUEST, "force is not valid '"+ sforce +"'");
		return;
	}
	int force = 0;
	try {
		force = Integer.parseInt(sforce);
	} catch(NumberFormatException e) {
		response.sendError(HttpServletResponse.SC_BAD_REQUEST, "force is not valid '"+ sforce +"'");
		return;
	}

	final GameManager gm = new GameManager();
	if (!gm.gameExists(id)) {
		response.sendError(HttpServletResponse.SC_BAD_REQUEST, "id does not exist '"+ id +"'");
		return;
	}
	final Game game = gm.loadGame(id);

	final AreaMap map = game.getMap();
	final Area from = map.getArea(fromId);
	final Area to   = map.getArea(toId);

	if (from == to) {
		response.sendError(HttpServletResponse.SC_BAD_REQUEST, "to = from '"+ to.getName() +" "+ from.getName() +"'");
		return;
	}

	int fromForce = from.getForce();
	int toForce   = to.getForce();

	from.setForce(fromForce - force);
	to.setForce(toForce + force);

	gm.storeGame(game);

	final JSONWriter writer = new JSONWriter2();
	final JSONFactory factory = new JSONFactory();
	writer.write(factory.create(game));

%><%= writer.toString() %>
